(function () {

    var backService = {
        //loading: 0
        requests: [],
        ajaxTimeout: 10000
    };

    backService.baseAppUrl = 'http://172.16.220.169:8080';// 服务器app前端链接

    backService.baseUrl = 'http://172.16.220.169:8080/app-server';// 服务器端app后台链接

    backService.localLoginInfo = JSON.parse(localStorage.getItem("loginInfo")) || null;

    backService.socket = null;

    backService.failureHandler = function (json) {
        if (json.status === 'abort') {
            //silent
            return;
        }
        else if (json.status === 'timeout') {
            app.alert('请求超时');
            return;
        }
        app.alert(json.msg);
        //alert(json.msg);
    };

    backService.get = function (url, data, callback, failure) {
        backService.ajax('GET', url, data, callback, failure);
    };

    backService.post = function (url, data, callback, failure) {
        backService.ajax('POST', url, data, callback, failure);
    };

    backService.requestToken = function (callback) {
        var lastLogin = JSON.parse(localStorage.lastLogin || 'null');
        if (!lastLogin) {
            alert('bad credential');
            return;
        }
        var url = backService.baseUrl + '/owner/request_token.json';
        $.ajax(url, {
            data: {
                account: lastLogin.id,
                password: lastLogin.pass
            },
            dataType: 'json',
            traditional: true,
            timeout: backService.ajaxTimeout,
            success: function (json) {
                backService.token = json.data;
                callback();
            },
            error: function (xhr, status, err) {
                alert(status + ': ' + err);
            }
        });
    };

    backService.ajax = function (method, url, data, callback, failure) {
        var ajaxArguments = arguments;
        if (typeof(data) === 'function') {
            failure = callback;
            callback = data;
        }
        //if (callback === undefined) {
        //    callback = data;
        //}
        if (failure === undefined) {
            failure = backService.failureHandler
        }
        if (url.indexOf('http:') == -1) {
            url = backService.baseUrl + url;
        }
        var completed = false;
        var showLoadingDelay = 500;
        if (backService.immediateLoading) {
            showLoadingDelay = 0;
            backService.immediateLoading = false;
        }
        var loadingCookie;
        if (backService.noLoading) {
            backService.noLoading = false;
        }
        else {
            setTimeout(function () {
                if (completed) {
                    return;
                }
                loadingCookie = app.showLoading();
            }, showLoadingDelay);
        }
        //++backService.loading;
        var headers = {};
        if (session.user && backService.token) {
            var ownerToken = backService.token + Number(session.user.id).toString(16);
            //headers['x-owner-token'] = ownerToken;
            headers['Accept'] = 'json-' + ownerToken;
        }


        var request = $.ajax(url, {
            method: method,
            data: data,
            dataType: 'json',
            traditional: true,
            timeout: backService.ajaxTimeout,
            headers: headers,
            // xhrFields: {
            //     withCredentials: true
            // },
            success: function (json) {
                completed = true;
                if (loadingCookie) {
                    app.hideLoading(loadingCookie);
                }
                if (json.ok) {
                    try {
                        callback && callback(json);
                    }
                    catch (e) {
                        if (inBrowser) {
                            throw e;
                        }
                        var loc = '[Ajax Callback Error]';
                        if (e.fileName) {
                            loc += '[' + e.fileName;
                            if (e.lineNumber) {
                                loc += ':' + e.lineNumber;
                            }
                            loc += ']';
                        }
                        console.log(loc + e.message);
                        if (app.debug && e.stack) {
                            console.log('>> ' + e.stack);
                        }
                    }
                }
                else {
                    if (json.error && json.msg == 'ERR::BAD_TOKEN' && !backService.ajax.inRequestTokenCallback) {

                        backService.requestToken(function () {
                            backService.ajax.inRequestTokenCallback = true;
                            backService.ajax.apply(this, ajaxArguments);
                        });
                    }
                    else {
                        failure(json);
                    }
                }
            },
            error: function (xhr, status, err) {
                if (!app.isBrowser) {

                    var networkState = app.checkConnection();
                    if (networkState == "none") {
                        err = "亲，网络断了，请检查网络连接";
                    }
                }
                failure({
                    ok: false,
                    status: status,
                    msg: status + ': ' + err
                });
            },
            complete: function (xhr, statusText) {
                if (statusText == 'timeout') {
                    request.abort();
                    app.showToast("网络超时!");
                }
                backService.ajax.inRequestTokenCallback = false;
                //--backService.loading;
                for (var n = 0; n < backService.requests.length; n++) {
                    if (backService.requests[n] === request) {
                        backService.requests.splice(n, 1);
                        break;
                    }
                }
                if (!completed) {
                    completed = true;
                    if (loadingCookie) {
                        app.hideLoading(loadingCookie);
                    }
                }
            }
        });
        backService.requests.push(request);
    };

    /**
     * 根据id获取文件数据
     * @param id
     * @param fallback
     * @returns {*}
     */
    backService.getFileUrl = function (id, fallback) {
        if (!id) {
            return fallback;
        }
        return backService.baseUrl + '/file/get.do?id=' + id + "&v=" + new Date().getTime();
    };

    /**
     * 设置用户登录信息
     * @param data
     * @param fallback
     */
    backService.setUserLoginInfo = function (data, fallback) {
        if (!data) {
            backService.localLoginInfo = fallback;
        }
        backService.localLoginInfo = JSON.parse(localStorage.getItem("loginInfo"));
    };

    /**
     * 清楚用户登录信息
     */
    backService.clearUserLoginInfo = function () {
        backService.localLoginInfo = null;
        localStorage.removeItem("loginInfo");
    };

    //
    backService.getIndexInfo = function (callback) {
        backService.get('/index/info.json', callback);
    };

    backService.onInitIndex = function (data, callback) {
        backService.post("/index/on_init_index.json", data, callback);
    };

    window.backService = backService;

})();
